﻿using System;
using System.Collections.Generic;

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

using Librarinth;

using SunwellRenderer.Simulation;

namespace SunwellRenderer.Rendering
{
	public class ShadowShader : ShaderEffect<BasicMaterial>
	{
		public ShadowShader() : base("HEXcontent/FX/SHADER/HCShader_Shadow") { }
		protected override void OnDraw(GraphicsDevice device,int cameraIndex,BufferArray<int> dataIndexes)
		{
			var models	= Parent.AllModels.Datas;
			var spatial	= SunwellMain.Instance.SpatialModule;
			var simulation	= SunwellMain.Instance.Simulation;
			var materials	= DataPool<BasicMaterial>.Datas;

			var lightMatrix	= Parent.CameraModule.CameraWorld(cameraIndex);

			Effect.Parameters["LightMatrix"].SetValue(lightMatrix);
			var distortCenter	= Vector3.Transform(new Vector3(0,0,-25),lightMatrix);
			Effect.Parameters["DistortCenter"].SetValue(Vector3.Normalize(distortCenter));
		
			Effect.CurrentTechnique	= Effect.Techniques["CreateShadowMap"];
			Effect.Begin();

			foreach(var dataIndex in dataIndexes)
			{
				var data	= Datas[dataIndex];
				var obj	= simulation.Datas[data.OBJIndex];

				Effect.Parameters["World"].SetValue(spatial.Datas[obj.SpatialIndex].World);
				Effect.Parameters["Texture"].SetValue(materials[data.MaterialIndex].Texture);

				Effect.CommitChanges();

				Parent.DrawMesh(device,Effect,models[data.ModelIndex].Model.Meshes[data.MeshIndex]);
			}

			Effect.End();
		}
	}
}
